package com.wanglianyun.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.Map;

/**
 * Description: redis的订阅发布机制是一种即时的消息机制，发布完消息之后并没有持久化消息，
 * 对于消息丢失敏感的场景不适用，redis的哨兵模式就是当主节点出故障时利用发布订阅机制来通知从节点更换主节点的
 * Copyright: Copyright (c) 2024
 * Create Time: 2024-11-11 16:41
 *
 * @author wanglianyun
 */
public class BiliLikeListener implements MessageListener {

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String msg = message.toString();
        Object parse = JSON.parse(message.toString());
        String channel = new String(message.getChannel());
        System.out.println("订阅到" + "channel: " + channel + "消息msg: " + msg + "，开始进行业务处理");
        //方式一解析发送的数据转成map
        Map<String, Object> map = JSON.parseObject(parse.toString(), new TypeReference<Map<String, Object>>(){});
        System.out.println(map);
        //方式二解析发送给的数据转对象
//        PublishRequest stringMap = JSON.parseObject(parse.toString(), new TypeReference<PublishRequest>(){});
//        System.out.println(stringMap.toString());
    }
}
